﻿using System;
using System.Collections.Generic;
using System.Data;

using Gurucore.Framework.Core;
using Gurucore.Framework.Core.Util;
using Gurucore.Framework.DataAccess;
using Gurucore.Framework.DataAccess.Persistence;

namespace #complex.Namespace#
{
	public sealed class #complex.Name#_Transformer : DTOTransformer
	{
		public #complex.Name#_Transformer()
		{
		}

		public override List<T> Transform<T>(System.Data.IDataReader p_reader, T p_sample)
		{
			List<T> arrDTO = new List<T>();
			List<string> arrColumn = new List<string>();
			for (int i = 0; i < p_reader.FieldCount; i++)
			{
				arrColumn.Add(p_reader.GetName(i));
			}

			TableInfoManager oTableInfoMgr = Application.GetInstance().GetGlobalSharedObject<TableInfoManager>();			
			DataAccessContext oDACtx = DataAccessContext.GetDataAccessContext();

			<ad:foreach collection="#complex.Elements#" var="element">			
			TableInfo oTableInfo_#element.Name# = oTableInfoMgr.GetTableInfo(typeof(#element.Name#));
			string sTablePrefix_#element.Name# = oTableInfo_#element.Name#.UseTablePrefix ? oDACtx.GetTablePrefix() : string.Empty;
			</ad:foreach>
			
			int nReadRow = 0;
			while (p_reader.Read())
			{
				<ad:foreach collection="#complex.elements#" var="element">			
				#element.Name# oDTO_#element.name# = new #element.Name#_Proxy();

				<ad:foreach collection="#element.Properties#" var="property">
				if (((arrColumn == null) || (arrColumn.Count == 0) || (arrColumn.Contains(sTablePrefix_#element.Name# + "#property.FieldName#"))) && (p_reader[sTablePrefix_#element.Name# + "#property.FieldName#"] != DBNull.Value))
				{
					((#element.Name#_Proxy)oDTO_#element.name#)._#property.Name# = (#property.Type#)Convert.ChangeType(p_reader[sTablePrefix_#element.Name# + "#property.FieldName#"], typeof(#property.Type#));
					((#element.Name#_Proxy)oDTO_#element.name#)._#property.Name#State = DTOColumnState.Unchanged;
				}
				</ad:foreach>
				</ad:foreach>
				
				T oDTO = AnonymousUtil.GetAnonymousActivator(p_sample)(p_sample
					<ad:foreach collection="#complex.elements#" var="element" index="i">
					,oDTO_#element.name# //new #element.name#()
					</ad:foreach>
				);

				arrDTO.Add(oDTO);
				nReadRow++;
			}
			return arrDTO;
		}
	}
}
